<template>
  <Dialog
    v-model:model-value="isShowDialog"
    :title="mode === 'edit' ? '编辑会员等级' : '新增会员等级'"
    append-to-body
    @opened="handleOpened"
    @closed="handleClosed"
    @confirm="handleConfirm(formRef)"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      :label-width="120"
    >
      <el-form-item
        label="会员权重"
        prop="memberLevel"
      >
        <el-select
          v-model="form.memberLevel"
          :disabled="form.id"
        >
          <el-option
            v-for="item in weightList"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <span class="tips">会员权重越大等级越高</span>
      </el-form-item>

      <el-form-item
        label="等级图标"
        prop="memberLogo"
      >
        <upload
          v-model:model-value="form.memberLogo"
          list-type="picture-card"
          :limit="1"
          @success="handleImgUploadSuccess"
        >
          <el-icon>
            <Plus />
          </el-icon>
        </upload>
      </el-form-item>
      <el-form-item
        label="等级名称"
        prop="memberName"
        class="common-form-width"
      >
        <el-input
          v-model="form.memberName"
          show-word-limit
          maxlength="20"
        />
      </el-form-item>
      <el-form-item
        label="等级描述"
        prop="levelDescription"
        class="common-form-width"
      >
        <el-input
          v-model="form.levelDescription"
          show-word-limit
          maxlength="200"
        />
      </el-form-item>
      <!--      外部会员-->
      <el-form-item
        v-if="memberConfig?.memberType === 2"
        label="等级code"
        class="common-form-width"
        prop="memberCode"
      >
        <el-input
          v-model="form.memberCode"
          show-word-limit
          maxlength="100"
        />
      </el-form-item>

      <!--      内部会员-->
      <el-form-item
        v-if="memberConfig?.memberType === 1"
        label="达标成长值"
        class="common-form-width"
        prop="growth"
      >
        <el-input
          v-model.number="form.growth"
          type="number"
        />
      </el-form-item>
      <el-form-item
        label="权益领取次数"
        prop="limit"
      >
        <div class="item-block">
          每人
        </div>
        <div class="item-block">
          <el-select v-model="form.timeType">
            <el-option
              v-for="item in unitOptions"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="item-block">
          领取
        </div>
        <div class="item-block">
          <el-input v-model="form.limitNum">
            <template #append>
              次
            </template>
          </el-input>
        </div>
      </el-form-item>
    </el-form>
<!--    <template #footer>-->
<!--      <el-button @click="handleCancel">-->
<!--        取消-->
<!--      </el-button>-->
<!--      <el-button-->
<!--        type="primary"-->
<!--        @click="handleConfirm"-->
<!--      >-->
<!--        确定-->
<!--      </el-button>-->
<!--    </template>-->
  </Dialog>
</template>

<script lang="ts" setup>
import type {FormInstance, FormRules} from "element-plus";
import { IMemberConfigRes, IRankItem, IVipRankAddData } from "@/api/modules/vipCenter";
import { addVipRank, editVipRank, getMemberConfig, getVipPayConfig } from "@/api/vipCenter";
import sysConfigApi from "@/api/sysConfigApi";
import ApiResult from "@/api/base/ApiResult";
import { getExternalConfigList } from "@/api/taskCenter";
import { IExternalConfigItem } from "@/api/modules/taskCenter";
import { useWeightList } from "@/views/vipCenter/compositions/useWeightList";
import { Ref } from "vue";
import { positiveInteger } from "@/utils/commonRegexp";
import { frequency } from "@/views/vipCenter/dict/frequency";

const props = defineProps<{
  show: boolean;
  mode: "edit" | "create";
  rowData: IRankItem;
  rankList: IRankItem[];
}>();
const emits = defineEmits(["update:show", "done"]);

const { weightList, getWeightList } = useWeightList()

const isShowDialog = computed({
  set(newValue) {
    emits("update:show", newValue);
  },
  get() {
    return props.show;
  },
});
const unitOptions = ref(frequency)

const formRef = ref();
const initForm: () => IVipRankAddData = () => {
  return {
    memberLogo: "",
    memberName: "",
    levelDescription: "",
    memberCode: "",
    memberSuperior: null,
    memberSubordinate: null,
    configId: null,
    externalMemberConfigId: '',
    growth: undefined,
    timeType: 'all',
    limitNum: null,
  };
};
const form = reactive<IVipRankAddData>(initForm());
const formRules = reactive<FormRules>({
  memberLevel: [{ required: true, trigger: "change", message: "请选择会员权重" }],
  memberLogo: [{ required: true, trigger: "blur", message: "请上传会员头像" }],
  memberName: [{ required: true, trigger: "blur", message: "请填写等级名称" }],
  levelDescription: [
    { required: true, trigger: "blur", message: "请填写等级描述" },
  ],
  growth: [
    {
      required: true, trigger: "blur", validator(rule: any, value: any, callback: any) {
        if (!positiveInteger.test("" + form.growth)) {
          callback("需为正整数")
          return
        }
        callback()
      }
    }
  ],
  memberCode: [{ required: true, trigger: "blur", message: "请填写等级Code" }],
  limit: [{
    trigger: 'blur',
    validator(rule: any, value: any, callback: any) {
      if (form.limitNum && !positiveInteger.test('' + form.limitNum)) {
        callback('限制次数只能为正整数')
      } else {
        callback()
      }
    }
  }]
  // configId: [{ required: true, trigger: "change", message: "请选择支付配置" }],
});


const memberConfig: Ref<IMemberConfigRes | undefined> = ref();
const _getMemberConfig = async () => {
  const rs = await getMemberConfig();

  if (rs.code === 200) {
    memberConfig.value = rs.payload
  }
}

const handleImgUploadSuccess = ({
  name,
  url,
}: {
  name: string;
  url: string;
}) => {
  form.memberLogo = url;
};

const payConfigList = ref<IExternalConfigItem[]>([]);
const _getVipPayConfig = async () => {
  const rs = await getExternalConfigList({ externalType: "pay" });
  if (rs.code === 200) {
    payConfigList.value = rs.payload ?? [];
  }
};

const handleSave = async (formRef:FormInstance) => {
  formRef.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      let rs;
      if (props.mode === "create") {
        if (props.rowData) {
          const rowIndex = props.rankList.findIndex(
            (item) => item.id === props.rowData.id
          );
          form.memberSuperior = props.rankList?.[rowIndex]?.id ?? null;
          form.memberSubordinate = props.rankList?.[rowIndex + 1]?.id ?? null;
        }

        rs = await addVipRank(form);
      } else {
        rs = await editVipRank(form);
      }

      if (rs.code === 200) {
        ElMessage.success("保存成功");
        handleDone();
      }
    } else {
      console.log("校验失败")
    }
  });
};

const handleDone = () => {
  isShowDialog.value = false;
  emits("done");
};

const handleConfirm = (formRef) => {
  handleSave(formRef);
};

const handleCancel = () => {
  isShowDialog.value = false;
};

const handleOpened = () => {
  if (props.mode === "edit") {
    Object.keys(props.rowData).forEach((key) => {
      form[key] = props.rowData[key];
    });
  }

  getWeightList();
  _getMemberConfig();
  // _getVipPayConfig();
};

const handleClosed = () => {
  formRef.value?.resetFields();
};
</script>

<style scoped lang="scss">
@use "@/components/goodsCenter/styles/common.scss";

.detail-container {
  .detail-text_line {
    white-space: nowrap;
  }
}

.tips {
  margin-left: 12px;
  color: #999;
  font-size: 14px;
}

.item-block {
  :deep(.el-select) {
    width: 100px;
  }

  :deep(.el-input__wrapper) {
    width: 100px;
  }
}

.item-block:not(:first-child) {
  margin-left: 10px;
}
</style>
